import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { forEach } from 'lodash';
import { MessageService, TreeNode } from '@iux/live';

@Component({
  selector: 'app-expand-collapse',
  templateUrl: './expand-collapse.component.html',
  styles: [
    `
      .tree-container {
        box-sizing: content-box;
        width: 3.6rem;
        padding: 0.16rem;
        border: 0.01rem solid #d9d9d9;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExpandCollapseComponent implements OnInit {
  data: TreeNode[];
  activeNode: TreeNode;

  constructor(private messageService: MessageService) {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = [
      {
        label: 'Documents',
        children: [
          {
            label: 'Expenses.doc',
            isLeaf: true,
          },
          {
            label: 'Resume.doc',
            isLeaf: true,
          },
        ],
      },
      {
        label: 'Word',
        children: [
          {
            label: 'Expenses.doc',
            isLeaf: true,
          },
          {
            label: 'Resume.doc',
            isLeaf: true,
          },
        ],
      },
      {
        label: 'Pictures',
        children: [
          {
            label: 'logo.png',
            isLeaf: true,
          },
          {
            label: 'banner.pnd',
            isLeaf: true,
          },
        ],
      },
    ];
  }

  expandAll() {
    this.toggle(this.data, true);
    this.data = [...this.data];
  }

  collapseAll() {
    this.toggle(this.data, false);
    this.data = [...this.data];
  }

  expandNode() {
    if (!this.activeNode) {
      return this.warn();
    }
    this.toggle([this.activeNode], true);
    this.data = [...this.data];
  }

  collapseNode() {
    if (!this.activeNode) {
      return this.warn();
    }
    this.toggle([this.activeNode], false);
    this.data = [...this.data];
  }

  toggleNode() {
    if (!this.activeNode) {
      return this.warn();
    }
    const status = !this.activeNode.expanded;
    status ? this.expandNode() : this.collapseNode();
  }

  toggle(nodes, status) {
    forEach(nodes, item => {
      item.expanded = status;
      this.toggle(item.children, status);
    });
  }

  checkNode({ node }) {
    this.activeNode = node;
    this.data = [...this.data]; // 刷新视图
  }

  warn() {
    this.messageService.warning('Need to choose a node');
  }
}
